
using System;

namespace MediaController.Extractor
{
    public class Statistics
    {
        
        private static readonly TimeSpan _zeroSpan = new TimeSpan(0L);
        private static readonly DateTime _zeroTime = new DateTime(0L);
        private long _bytesExtracted;
        private DateTime _ended = _zeroTime;
        private ExtractionProgressEventArgs _lastSample;
        private string _name;
        private double _percentComplete;
        private Statistics _split;
        private DateTime _started = _zeroTime;

        
        public Statistics(string name)
        {
            _name = name;
        }

        // Properties
        public double Bandwidth
        {
            get
            {
                TimeSpan timeElapsed = TimeElapsed;
                if (timeElapsed == _zeroSpan)
                {
                    return 0.0;
                }
                return (((BytesExtracted) / timeElapsed.TotalMilliseconds) * 1000.0);
            }
        }

        public long BytesExtracted
        {
            get { return _bytesExtracted; }
        }

        public long FileSize
        {
            get
            {
                if (_lastSample == null)
                {
                    return 0L;
                }
                return _lastSample.FileSize;
            }
        }

        public double PercentCompleate
        {
            get { return _percentComplete; }
        }

        public Statistics Split
        {
            get { return _split; }
        }

        public TimeSpan TimeElapsed
        {
            get
            {
                if (!(_started == _zeroTime))
                {
                    return (((_ended == _zeroTime) ? DateTime.Now : _ended) - _started);
                }
                return _zeroSpan;
            }
        }

        public void AddSample(ExtractionProgressEventArgs progress)
        {
            if (_split != null)
            {
                _split.AddSample(progress);
            }
            _lastSample = progress;
            _percentComplete = progress.PercentComplete;
            _bytesExtracted += progress.DataLength;
        }

        internal void Begin()
        {
            _started = DateTime.Now;
            _ended = _zeroTime;
            _split = null;
            _bytesExtracted = 0L;
            _percentComplete = 0.0;
            _lastSample = null;
        }

        ~Statistics()
        {
        }

        public void InitSplit(string name)
        {
            if (_split == null)
            {
                Begin();
            }
            _split = new Statistics(name);
            _split.Begin();
        }

        public bool IsStarted()
        {
            return _started.Equals(_zeroTime);
        }
    }
}

